<?php

namespace BinContainerPacking;

class Package
{
    /**
     * @var Bin[]
     */
    private array $bins = [];

    /**
     * @var Item[]
     */
    private array $items = [];

    public function __construct()
    {
    }


    /**
     * @param Bin $bin
     * @return void
     */
    public function addBin(Bin $bin)
    {
        $this->bins[] = $bin;
    }

    /**
     * @param Item $item
     * @return void
     */
    public function addItem(Item $item)
    {
        $this->items[] = $item;
    }


    /**
     * 箱子排序 用的冒泡
     */
    function sortBin()
    {
        $count = count($this->bins);
        $container = $this->bins;
        for ($j = 1; $j < $count; $j++) {
            for ($i = 0; $i < $count - $j; $i++) {
                if ($container[$i]->getVolume() > $container[$i + 1]->getVolume()) {
                    $temp = $container[$i];
                    $container[$i] = $container[$i + 1];
                    $container[$i + 1] = $temp;
                }
            }
        }
        $this->bins = $container;
    }

    /**
     * 打包
     * @return array
     */
    public function pack(): array
    {
        $this->sortBin();

        $bins = [];
        foreach ($this->bins as $bin) {
            if ($bin->putItems($this->items)) {
                $bins[] = $bin;
            }
        }
        return $bins;
    }

    /**
     * @return Bin[]
     */
    public function getBins(): array
    {
        return $this->bins;
    }

    /**
     * @param Bin[] $bins
     */
    public function setBins(array $bins): void
    {
        foreach ($bins as $bin) {
            $this->addBin($bin);
        }
    }

    /**
     * @return Item[]
     */
    public function getItems(): array
    {
        return $this->items;
    }

    /**
     * @param Item[] $items
     */
    public function setItems(array $items): void
    {
        foreach ($items as $item) {
            $this->addItem($item);
        }
    }
}